<template>
  <div class="container-login">
    <el-card>
      <img class="logo" src="../../assets/logo_index.png" alt />

      <el-form ref="loginGlobel" :model="loginForm" :rules="loginRules">
        <el-form-item prop="mobile">
          <el-input v-model="loginForm.mobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            style="width:240px;margin-right:8px"
            v-model="loginForm.code"
            placeholder="请输入验证码"
          ></el-input>
          <el-button>获取验证码</el-button>
        </el-form-item>

        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意相关条款</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="login()" type="primary" style="width:100%">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import auth from "@/utils/auth";

export default {
  // 当时路由来渲染组件，会使用name指定的组件名称，没指定默认是文件的名称
  // Vue.component() components选项注册组件，组件的名字是自己定义和name无关。
  name: "login-page",
  data() {
    const checkMobile = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value))
        return callback(new Error("请填写正确的手机号"));
      callback();
    };

    return {
      loginForm: {
        mobile: "",
        code: ""
      },
      loginRules: {
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { len: 6, message: "请输入六位数字", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    login() {
      this.$refs.loginGlobel.validate(async valid => {
        if (valid) {
          //   this.$http.post('/authorizations', this.loginForm).then(res=>{
          //       auth.setUser(res.data.data)
          //       this.$router.push('/')
          //   }).catch(()=>{
          //       this.$message.error('手机号或验证码输入有误')
          //   })

          try {
            const res = await this.$http.post("/authorizations", this.loginForm);
            auth.setUser(res.data.data);
            this.$router.push("/");
          } catch (error) {
              this.$message.error('手机号或验证码输入有误')
          }
        }
      });
    }
  }
};
</script>

<style scoped lang='less'>
.container-login {
  width: 100%;
  height: 100%;
  background: url("../../assets/login_bg.jpg") no-repeat center / cover;
  position: absolute;
  top: 0;
  left: 0;
}
.el-card {
  width: 400px;
  height: 350px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.logo {
  display: block;
  width: 200px;
  margin: 0 auto 20px;
}
</style>